<template>
  <view class="chat-page">
    <!-- 聊天头部 -->
    <view class="chat-header">
      <image src="/static/ai.png" class="ai-avatar"></image>
      <view class="ai-info">
        <text class="ai-name">AI健康顾问</text>
        <text class="ai-status">在线</text>
      </view>
    </view>

    <!-- 消息列表 -->
    <scroll-view class="messages-container" scroll-y :scroll-into-view="scrollIntoView">
      <view
        v-for="message in messages"
        :key="message.id"
        :id="'msg-' + message.id"
        class="message"
        :class="{ 'user-message': message.sender === 'user' }"
      >
        <view class="message-avatar">
          <image
            :src="message.sender === 'user' ? '/static/user.png' : '/static/ai.png'"
            class="avatar-img"
          ></image>
        </view>
        <view class="message-content">
          <view class="message-bubble" :class="{ 'user-bubble': message.sender === 'user' }">
            <text class="message-text">{{ message.content }}</text>
          </view>
          <text class="message-time">{{ formatTime(message.timestamp) }}</text>
        </view>
      </view>

      <!-- AI正在输入 -->
      <view v-if="isTyping" class="message" id="typing-msg">
        <view class="message-avatar">
          <image src="/static/ai.png" class="avatar-img"></image>
        </view>
        <view class="message-content">
          <view class="message-bubble typing-bubble">
            <view class="typing-dots">
              <view class="dot"></view>
              <view class="dot"></view>
              <view class="dot"></view>
            </view>
          </view>
        </view>
      </view>
    </scroll-view>

    <!-- 快捷问题 -->
    <view v-if="messages.length === 1" class="quick-questions">
      <text class="quick-title">常见问题：</text>
      <view class="questions-list">
        <view
          v-for="question in quickQuestions"
          :key="question"
          class="question-btn"
          @tap="selectQuickQuestion(question)"
        >
          <text class="question-text">{{ question }}</text>
        </view>
      </view>
    </view>

    <!-- 输入框 -->
    <view class="chat-input">
      <input
        v-model="inputValue"
        type="text"
        placeholder="输入您的健康问题..."
        class="input-field"
        @confirm="sendMessage"
        confirm-type="send"
      />
       <view class="send-btn" @tap="sendMessage">
        <text class="send-icon">📤</text>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, nextTick } from 'vue'

const BASE_URL = 'https://openrouter.ai/api/v1/chat/completions'
const API_KEY = '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'

const messages = ref([
  {
    id: 1,
    content: '您好！我是您的AI健康顾问，有什么健康问题可以咨询我。',
    sender: 'ai',
    timestamp: new Date()
  }
])

const inputValue = ref('')
const isTyping = ref(false)
const scrollIntoView = ref('')

const quickQuestions = ref([
  '如何改善睡眠质量？',
  '健康减肥的方法',
  '如何缓解工作压力？',
  '营养均衡的饮食建议'
])

// 发送消息
const sendMessage = async () => {
  if (!inputValue.value.trim()) return

  const userMessage = {
    id: Date.now(),
    content: inputValue.value,
    sender: 'user',
    timestamp: new Date()
  }

  messages.value.push(userMessage)
  const question = inputValue.value
  inputValue.value = ''
  isTyping.value = true

  nextTick(() => {
    scrollIntoView.value = 'msg-' + userMessage.id
  })

  try {
    const aiText = await getAIResponse(question)

    // 打印 AI 返回的文字内容
    console.log('🟢 AI 返回内容：', aiText)

    const aiResponse = {
      id: Date.now() + 1,
      content: aiText,
      sender: 'ai',
      timestamp: new Date()
    }
    messages.value.push(aiResponse)
  } catch (error) {
    console.error('❌ 获取AI回复失败：', error)
    messages.value.push({
      id: Date.now() + 2,
      content: '抱歉，获取AI回复失败，请稍后重试。',
      sender: 'ai',
      timestamp: new Date()
    })
  } finally {
    isTyping.value = false
    nextTick(() => {
      scrollIntoView.value = 'msg-' + messages.value[messages.value.length - 1].id
    })
  }
}

// 调用 OpenRouter AI 接口
const getAIResponse = (question) => {
  const prompt = `请用中文回答以下问题，要求：
## 按1,2,3排好序回答
## 内容不超过200字
问题：${question}`

  return new Promise((resolve, reject) => {
    uni.request({
      url: BASE_URL,
      method: 'POST',
      header: {
        Authorization: `Bearer ${API_KEY}`,
        'Content-Type': 'application/json'
      },
      data: {
        model: 'openai/gpt-4.1',
        messages: [{ role: 'user', content: prompt }],
        max_tokens: 400
      },
      success: (res) => {
        if (res.statusCode === 200 && res.data?.choices?.[0]?.message?.content) {
          resolve(res.data.choices[0].message.content.trim())
        } else {
          reject(new Error('API 返回数据格式不正确'))
        }
      },
      fail: (err) => reject(err)
    })
  })
}

// 快捷问题选择
const selectQuickQuestion = (question) => {
  inputValue.value = question
}

// 格式化时间
const formatTime = (date) => {
  const hours = date.getHours()
  const minutes = date.getMinutes().toString().padStart(2, '0')
  let period = ''

  if (hours >= 6 && hours < 12) {
    period = '上午'
  } else if (hours >= 12 && hours < 18) {
    period = '下午'
  } else {
    period = '晚上'
  }

  // 12小时制显示小时
  const hour12 = hours % 12 === 0 ? 12 : hours % 12

  return `${period} ${hour12}:${minutes}`
}


// Markdown解析：将 **加粗** 转为 <text style="font-weight:bold">加粗</text>，换行转<br/>
const parseMarkdown = (text) => {
  if (!text) return ''
  return text
    .replace(/\*\*(.+?)\*\*/g, (_, p1) => `<text style="font-weight:bold">${p1}</text>`)
    .replace(/\n/g, '<br/>')
}
</script>



<style scoped>
.chat-page {
  display: flex;
  flex-direction: column;
  height: 100vh;
  background: #f9fafb;
}

.chat-header {
  background: white;
  padding: 32rpx;
  border-bottom: 1px solid #e5e7eb;
  display: flex;
  align-items: center;
  gap: 24rpx;
}

.ai-avatar {
  width: 80rpx;
  height: 80rpx;
  border-radius: 50%;
  background: #f3f4f6;
}

.ai-name {
  font-weight: 600;
  color: #1f2937;
  display: block;
  font-size: 32rpx;
}

.ai-status {
  font-size: 28rpx;
  color: #10b981;
  display: block;
}

.messages-container {
  flex: 1;
  padding: 32rpx;
}

.message {
  display: flex;
  gap: 24rpx;
  margin-bottom: 32rpx;
  margin-right: 35rpx;
}

.message.user-message {
  flex-direction: row-reverse;
}

.message-avatar {
  width: 64rpx;
  height: 64rpx;
  border-radius: 50%;
  flex-shrink: 0;
}

.avatar-img {
  width: 64rpx;
  height: 64rpx;
  border-radius: 50%;
}

.message-content {
  max-width: 80%;
}

.message-bubble {
  background: white;
  padding: 24rpx;
  border-radius: 32rpx;
  margin-bottom: 8rpx;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
}

.user-bubble {
  background: #3b82f6;
}

.message-text {
  font-size: 28rpx;
  line-height: 1.6;
  color: #1f2937;
}

.user-bubble .message-text {
  color: white;
}

.message-time {
  font-size: 24rpx;
  color: #6b7280;
  text-align: right;
  display: block;
}

.user-message .message-time {
  text-align: left;
}

.typing-bubble {
  background: white;
  padding: 24rpx;
  border-radius: 32rpx;
}

.typing-dots {
  display: flex;
  gap: 8rpx;
  justify-content: center;
}

.dot {
  width: 12rpx;
  height: 12rpx;
  background: #6b7280;
  border-radius: 50%;
  animation: typing 1.4s infinite ease-in-out;
}

.dot:nth-child(2) {
  animation-delay: 0.2s;
}

.dot:nth-child(3) {
  animation-delay: 0.4s;
}

@keyframes typing {
  0%, 80%, 100% {
    transform: scale(0.8);
    opacity: 0.5;
  }
  40% {
    transform: scale(1);
    opacity: 1;
  }
}

.quick-questions {
  padding: 32rpx;
  border-top: 1px solid #e5e7eb;
  background: white;
}

.quick-title {
  font-size: 28rpx;
  color: #6b7280;
  display: block;
  margin-bottom: 16rpx;
}

.questions-list {
  display: flex;
  flex-wrap: wrap;
  gap: 16rpx;
}

.question-btn {
  background: #f3f4f6;
  border: 1px solid #d1d5db;
  border-radius: 32rpx;
  padding: 16rpx 24rpx;
  transition: all 0.2s;
}

.question-btn:active {
  background: #e5e7eb;
  border-color: #9ca3af;
}

.question-text {
  font-size: 24rpx;
  color: #374151;
}

.chat-input {
  display: flex;
  gap: 16rpx;
  padding: 32rpx;
  border-top: 1px solid #e5e7eb;
  background: white;
}

.input-field {
  flex: 1;
  padding: 24rpx;
  border: 1px solid #d1d5db;
  border-radius: 48rpx;
  font-size: 28rpx;
  background: #f9fafb;
}

.send-btn {
  width: 80rpx;
  height: 80rpx;
  background: #3b82f6;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: background-color 0.2s;
}

.send-btn:active {
  background: #2563eb;
}

.send-icon-img {
  width: 10rpx;
  height: 10rpx;
}
</style>
